package com.xuzao.developer.config;

import com.xuzao.developer.annotation.MethodAnnotation;
import com.xuzao.developer.annotation.ModuleAnnotation;
import com.xuzao.developer.base.model.SysResource;
import com.xuzao.developer.dao.SysResourceDao;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author xuzao
 * @description
 * @date 2019-09-19 09:47
 */
@Component
public class InitResource implements InitializingBean {
    @Resource
    private SysResourceDao sysResourceDao;

    @Override
    public void afterPropertiesSet() throws Exception {
        insertResource();
    }

    public void insertResource() {
        sysResourceDao.deleteAll();
        Set<Class<?>> classList = getClasses("com.xuzao.developer.controller");
        Object[] ts = classList.toArray();
        for (Object t : ts) {
            Class<?> c = (Class<?>) t;
            ModuleAnnotation moduleAnnotation = c.getAnnotation(ModuleAnnotation.class);
            if (null != moduleAnnotation) {
                String heardUrl = c.getAnnotation(RequestMapping.class).value()[0];
                String heardName = moduleAnnotation.name();

                Method[] methods = c.getMethods();

                if (methods != null) {
                    for (Method method : methods) {
                        MethodAnnotation methodAnnotation = method.getAnnotation(MethodAnnotation.class);
                        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                        String url = "";
                        String name;
                        if (null != methodAnnotation) {
                            name = heardName + "-" + methodAnnotation.name();
                            if (null != requestMapping) {
                                url = heardUrl + requestMapping.value()[0];
                            }
                            SysResource sysResource = new SysResource();
                            sysResource.setName(name);
                            sysResource.setUrl(url);
                            sysResourceDao.insert(sysResource);
                        }
                    }
                }
            }
        }
    }

    /**
     * 从包package中获取所有的Class
     *
     * @param pack
     * @return
     */
    public Set<Class<?>> getClasses(String pack) {

        Set<Class<?>> classes = new LinkedHashSet<>();
        boolean recursive = true;
        String packageName = pack;
        String packageDirName = packageName.replace('.', '/');
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();
                String protocol = url.getProtocol();
                if ("file".equals(protocol)) {
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
                } else if ("jar".equals(protocol)) {
                    JarFile jar;
                    try {
                        jar = ((JarURLConnection) url.openConnection()).getJarFile();
                        Enumeration<JarEntry> entries = jar.entries();
                        while (entries.hasMoreElements()) {
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            if (name.charAt(0) == '/') {
                                name = name.substring(1);
                            }
                            if (name.startsWith(packageDirName)) {
                                int idx = name.lastIndexOf('/');
                                if (idx != -1) {
                                    packageName = name.substring(0, idx).replace('/', '.');
                                }
                                if ((idx != -1) || recursive) {
                                    if (name.endsWith(".class") && !entry.isDirectory()) {
                                        String className = name.substring(packageName.length() + 1, name.length() - 6);
                                        try {
                                            classes.add(Class.forName(packageName + '.' + className));
                                        } catch (ClassNotFoundException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return classes;
    }

    /**
     * 以文件的形式来获取包下的所有Class
     *
     * @param packageName
     * @param packagePath
     * @param recursive
     * @param classes
     */
    public void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive,
                                                 Set<Class<?>> classes) {
        File dir = new File(packagePath);
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        File[] dirfiles = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
            }
        });
        for (File file : dirfiles) {
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive,
                        classes);
            } else {
                String className = file.getName().substring(0, file.getName().length() - 6);
                try {
                    classes.add(
                            Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
